<?php


namespace app\service;


use app\entity\ActApplyEntity;
use app\entity\ActListEntity;
use app\exception\ErrorCode;
use app\exception\OaException;
use app\models\request\ReqActListPage;
use app\models\request\ReqApplyAct;
use app\models\request\ReqApplyUpdate;
use app\models\request\ReqLogistics;
use app\models\response\RespPage;
use yii\data\Pagination;


class ApplyService
{

    /**
     * @param $userId
     * @param $actId
     * @return array|\yii\db\ActiveRecord|ActApplyEntity
     * @throws OaException
     */
    public function findByUserIdAndActId($actId,$userId){

        $query = ActApplyEntity::find()->where(["user_id"=>$userId,"act_id"=>$actId,"del_flag"=>0])    ->andWhere(['in', 'sh_status', [0, 1]]);



        $entity = $query->one();

        if(!$entity) {
            throw new OaException(ErrorCode::NOT_404);
        }
        return $entity;
    }


    /**
     * @param $id
     * @param $userId
     * @return array|\yii\db\ActiveRecord|ActApplyEntity
     * @throws OaException
     */
    public function findByIdAndUserId($id,$userId){
        $entity = ActApplyEntity::find()->where(["id"=>$id,"user_id"=>$userId,"sh_status"=>1])->one();
        if(!$entity) {
            throw new OaException(ErrorCode::NOT_404);
        }
        return $entity;
    }


    /**
     * @param $id
     * @return array|\yii\db\ActiveRecord|ActApplyEntity
     * @throws OaException
     */
    public function findById($id){
        $entity = ActApplyEntity::find()->where(["id"=>$id])->one();
        if(!$entity) {
            throw new OaException(ErrorCode::NOT_404);
        }
        return $entity;
    }


    public function update(ReqApplyUpdate  $req) {
        $e = $this->findById($req->getApplyId());
        if(in_array($e->getStatus(),[3])) {
            throw new OaException(ErrorCode::ACT_STATUS_ERR);
        }
        $e->setStatus(0);
        $e->setActTime(json_encode($req->getActTime()));
        $e->setActNum(count($req->getActTime()));
        $e->setShStatus(0);

        $e->setUpdateTime(date("Y-m-d G:i:s"));
        $e->save();
    }


    public function apply(ReqApplyAct  $req) {
        $service = new ActService();
        $actDetail = $service->findByPk($req->getActId());



        if(time() <  strtotime($actDetail->getApplyBeginTime()) ){
            throw new OaException(ErrorCode::ACT_NO_START);
        }

        if(time() >  strtotime($actDetail->getApplyEndTime()) ){
            throw new OaException(ErrorCode::ACT_FINISHED);
        }



        foreach($req->getActTime() as $r) {
            if(strtotime($r["beginTime"]) <  strtotime($actDetail["beginTime"]) ){
                throw new OaException(ErrorCode::ACT_BEGIN_TIME_ERR);
            }

            if(strtotime($r["endTime"]) >  strtotime($actDetail["endTime"]) ){
                throw new OaException(ErrorCode::ACT_END_TIME_ERR);
            }
        }




        try {
            $this->findByUserIdAndActId($req->getActId(), $req->getUserId());

        } catch (OaException $e) {
            $e = new ActApplyEntity();
            $e->setUserId($req->getUserId());
            $e->setActId($req->getActId());
            $e->setStatus(0);

            $e->setActTime(json_encode($req->getActTime()));
            $e->setActNum(count($req->getActTime()));


            $e->setCreateTime(date("Y-m-d G:i:s"));
            $e->setUpdateTime(date("Y-m-d G:i:s"));
            $e->setDelFlag(0);
            $e->setExpressStatus(0);
            $e->save();
            return true;
        }
        throw new OaException(ErrorCode::APPLIED);
    }


    /**
     * @param ReqActListPage $req
     * @return RespPage
     */
    public function listPage(ReqActListPage  $req) {
        $data = ActApplyEntity::find()->where(["del_flag"=>0,])->orderBy("id desc");
        if ($req->getUserId()) {
            $data->andWhere(["user_id"=>$req->getUserId()]);
        }
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => $req->getPageSize(),'page'=>$req->getPageNo()-1]);
        /**@var $entities ActApplyEntity[]*/
        $entities = $data->offset($pages->getOffset())->limit($pages->getLimit())->all();
        $list = [];
        foreach ($entities as $entity) {

            $actEntity = $entity->act;


            array_push($list,[
                "id"=>$entity->getId(),
                "actId"=>$actEntity->getId(),
                "title"=>$actEntity->getTitle(),
                "beginTime"=>$actEntity->getBeginTime(),
                "endTime"=>$actEntity->getEndTime(),
                "picUrl"=>$actEntity->getPicUrl(),
                "status"=>$entity->getStatus(),
                "express_no"=>$entity->getExpressNo(),
                "actTime"=>json_decode($entity->getActTime(),true),
                "express_company"=>$this->getExpressCompany($entity->getExpressCompanyCode()),
                "trainMaterial"=>$actEntity->getTrainMaterial(),
                "feedbackMaterial"=>$actEntity->getFeedbackMaterial(),
                "materialInfo"=>json_decode($actEntity->getMaterialInfo(),true),
            ]);
        }

        $resp = new RespPage();
        $resp->setTotal(intval($pages->totalCount));
        $resp->setPageSize($pages->getPageSize());
        $resp->setPageNo($req->getPageNo());
        $resp->setList($list);
        return $resp;
    }

    public function getExpressCompany($key){
        if (!$key) return "";

        $arr =  [
            ""=>"",
            "yuantong" => "圆通速递",
            "zhongtong" => "中通快递",
            "yunda" => "韵达快递",
            "shentong" => "申通快递",
            "jtexpress" => "极兔速递",
            "youzhengguonei" => "邮政快递包裹",
            "shunfeng" => "顺丰速运",
            "ems" => "EMS",
            "jd" => "京东物流",
            "youzhengbk" => "邮政标准快递",
            "debangkuaidi" => "德邦快递",
            "shunfengkuaiyun" => "顺丰快运",
            "debangwuliu" => "德邦",
            "danniao" => "丹鸟",
            "zhongtongkuaiyun" => "中通快运",
            "annengwuliu" => "安能快运",
            "lianhaowuliu" => "联昊通",
            "jingdongkuaiyun" => "京东快运",
            "subida" => "速必达",
            "kuayue" => "跨越速运"
        ];
        return isset($arr[$key])?$arr[$key]:$key;
    }

    public function getLogistics(ReqLogistics $req) {
        $activeRecord = $this->findByUserIdAndActId($req->getId(), $req->getUserId());
        if ($activeRecord->getExpressStatus() == 0) {
            throw new OaException(ErrorCode::ORDER_NOT_FH);
        }
        if ($activeRecord->getExpressStatus()== 1) {
            if (!$activeRecord->getExpressDetail() || time()-strtotime($activeRecord->getUpdateTime())>3600) {
                $arr = $this->getKuai100($activeRecord->getExpressCompanyCode(), $activeRecord->getExpressNo(), "");
                foreach ($arr as $r) {
                    if ($r["status"] == "签收") {
                        $activeRecord->setExpressStatus(2);
                    }
                    break;
                }
                $activeRecord->setExpressDetail(json_encode($arr));
                $activeRecord->setUpdateTime(date("Y-m-d G:i:s"));
                $activeRecord->save();
            }
        }
        return json_decode($activeRecord->getExpressDetail(),true);
    }

    /**
     * @param $company
     * @param $code
     * @param $phone
     * @return mixed
     * @throws OaException
     */
    public function getKuai100($company,$code,$phone){


        //参数设置
        $key = 'LzntZLoc4150';                        // 客户授权key
        $customer = '8B5C9C39CDCC9A0945CA21590FC1BCF0';                   // 查询公司编号
        $param = array(
            'com' => $company,             // 快递公司编码
            'num' => $code,     // 快递单号
            'phone' => $phone,                // 手机号
            'from' => '',                 // 出发地城市
            'to' => '',                   // 目的地城市
            'resultv2' => '1',            // 开启行政区域解析
            'show' => '0',                // 返回格式：0：json格式（默认），1：xml，2：html，3：text
            'order' => 'desc'             // 返回结果排序:desc降序（默认）,asc 升序
        );

        //请求参数
        $post_data = array();
        $post_data['customer'] = $customer;
        $post_data['param'] = json_encode($param, JSON_UNESCAPED_UNICODE);
        $sign = md5($post_data['param'] . $key . $post_data['customer']);
        $post_data['sign'] = strtoupper($sign);

        $url = 'https://poll.kuaidi100.com/poll/query.do';    // 实时查询请求地址

        /* echo '请求参数：<br/><pre>';
         echo print_r($post_data);
         echo '</pre>';*/

        // 发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        // 第二个参数为true，表示格式化输出json
        $data = json_decode($result, true);
        if (isset($data["status"]) && $data["status"]==200) {
            return $data["data"];
        }
        throw new OaException(["500"=>$data["message"]]);
    }
    
    



}